// Set Action Button
var setAction = function(option) {
    if ($.isArray(option)) {
        $('#action_bar').html('').hide();
		var ln_total = option.length;
        $(option).each(function(i, btn) {
            var ls_label = (btn.label != undefined ? btn.label : '');
            var ls_icon = (btn.icon != undefined ? btn.icon : '');
            var lf_click = (btn.onclick != undefined && typeof (btn.onclick) == 'function' ? btn.onclick : function() { });
			
			// Set Permission
			var lb_allow_this_button	= true;
			if(ls_label.toLowerCase()=='add'){
				if(gs_permission_c != '1'){ lb_allow_this_button = false; }
			}
			
			if(ls_label.toLowerCase()=='retrieve'){
				if(gs_permission_r != '1'){ lb_allow_this_button = false; }
			}
			
			if(ls_label.toLowerCase()=='edit'){
				if(gs_permission_u != '1'){ lb_allow_this_button = false; }
			}
			
			if(ls_label.toLowerCase()=='delete'){
				if(gs_permission_d != '1'){ lb_allow_this_button = false; }
			}
			
			if(ls_label.toLowerCase()=='print'){
				if(gs_permission_pr != '1'){ lb_allow_this_button = false; }
			}
			
			if(ls_label.toLowerCase()=='download'){
				if(gs_permission_dw != '1'){ lb_allow_this_button = false; }
			}
			
			if(ls_label.toLowerCase()=='upload'){
				if(gs_permission_up != '1'){ lb_allow_this_button = false; }
			}
			
            //var $button = $('<button>').bind('click', lf_click);
            //if (ls_icon != '') $button.append($('<img>').attr('style', 'height:15px;float:left;padding:1px 5px 0px 0px;').attr('src', gs_path + '/Content/images/' + ls_icon));
			
			if(lb_allow_this_button){
				$button = $('<a>').attr('id', 'btn_act'+i).bind('click', lf_click).addClass('easyui-linkbutton').attr('iconCls', 'icon-'+ls_icon).css('float','left');
				$('#action_bar').append($button.append(ls_label));
			}
			/*if((i+1) < ln_total){
				$('#action_bar').append('<div class="datagrid-btn-separator"></div>');
			}*/
        });
		
		$('#action_bar > a').linkbutton({ plain:true });
        $('#action_bar')/*.buttonset()*/.fadeIn();
    }
};

// updateRowFlag (Patching Flag Update)
var updateRowFlag = function(gridname, row){
	var gridInfo		= $('#'+gridname).data('datagrid');
	var updatedRows		= gridInfo.updatedRows;
	var idField			= gridInfo.options.idField;
	var lnIndex			= -1;
	$(updatedRows).each(function(i,el){
		var lb_isrow = false;
		try{ eval('lb_isrow = (el.'+idField+' == row.'+idField+');'); }catch(e){}
		if(lb_isrow){ lnIndex = i; }
	});
	if(lnIndex>=0){ updatedRows[lnIndex]=row; }else{ updatedRows = updatedRows.concat(row); }
	gridInfo.updatedRows = updatedRows;
	$('#'+gridname).data('datagrid', gridInfo);
};

// Set Loading
var setLoading = function(ab_set) {
    if (ab_set == undefined) ab_set = true;

    if (ab_set) {
        try {
            winWidth = document.all ? document.body.clientWidth : window.innerWidth;
        } catch (er) { winWidth = screen.width; }
        try {
            winHeight = document.all ? document.body.clientHeight : window.innerHeight;
        } catch (er) { winHeight = screen.height; }

        $('#content_block').css('width', winWidth + 'px').css('height', winHeight + 'px').hide();
        var ln_left = (winWidth - 250) / 2; if (ln_left < 0) ln_left = 0;
        var ln_top = (winHeight - 350) / 2; if (ln_top < 0) ln_top = 0;
        $('#content_loading').css('left', ln_left + 'px').css('top', ln_top + 'px').hide();
        
        $('#content_block, #content_loading').show(); 
    } else { $('#content_block, #content_loading').hide(); }
};

// Resizing Browser
var containerResize = function() {
    try {
        winWidth = document.all ? document.body.clientWidth : window.innerWidth;
    } catch (er) { winWidth = screen.width; }
    try {
        winHeight = document.all ? document.body.clientHeight : window.innerHeight;
    } catch (er) { winHeight = screen.height; }
    
    // Put Action Here
};

// Add Log (For Developer Usage in order to debug without firebug in Production Client)
var addLog = function(as_message, as_type) {
    if (debug == undefined || debug == null || !debug) return false;
    
    if (as_type == undefined) as_type == '';
    var $divLog = $('<div>').addClass('debuglist');
    if (as_type != '') { $divLog.addClass(as_type); }
    var ls_now = formatDate(now, 'dd month yyyy') + ' ' + str_pad(now.getHours(), 2, '0', 'STR_PAD_LEFT') + ":" + str_pad(now.getMinutes(), 2, '0', 'STR_PAD_LEFT') + ":" + str_pad(now.getSeconds(), 2, '0', 'STR_PAD_LEFT');
    $divLog.html('<span class="time" style="color:#CCC;float:left;font-size:10px;margin-top:-5px;">' + ls_now + '</span><br />').append(as_message);
	$('#content_debug .dialog-content').append($divLog).prop({ scrollTop: $("#content_debu .dialog-content").prop("scrollHeight") });
};

// Load Page Content
var loadPage = function(as_url, ao_option) {
    if (as_url == undefined || as_url == '' || as_url == '#') return false;
    if (str_left(as_url.toLowerCase(), 11) == '/app/system') { as_url = Base64Decode('L0FwcC9EYXNoYm9hcmQ='); }
    setLoading(); $('div.window').remove();
    var ls_url = (str_left(as_url,4)=='http' || str_left(as_url,3)=='www' ? '' : gs_path) + as_url;
	var ls_menu_id = ''; try{ ls_menu_id=(ao_option.menu_id==undefined?'':ao_option.menu_id); }catch(e){}
    addLog('Request Page : <a href="' + ls_url + '">' + ls_url + '</a>');
	
	// Remove Cache UI
	$obj = $('#if_download');var i = 0;while($obj.length > 0){$next_obj = $obj.next();if($obj.hasClass('window-mask') || $obj.hasClass('window-shadow')){$next_obj = $obj.next();$obj.remove();}$obj = $next_obj;i++;}

    $.ajax({
        type: 'POST', url: ls_url, cache: false, data: { ajax: '0', culture: gs_localize,session_menu_id:ls_menu_id,  sessid: sessid },
        success: function(data) { $('#container, #action_bar').html(''); setLoading(false); addLog('Response Page From [<a href="' + ls_url + '">' + ls_url + '</a>]<br />' + nl2br(htmlentities(data)), 'success'); $('#container').html(data); setLoading(false); if (debug) { $('.debug_url').show(); } else { $('.debug_url').hide(); } uniform(); /*$('#container').hide().slideDown('slow');*/ },
        error: function(xhr, ajaxOptions, thrownError) { var ls_message = ''; var ls_logmessage = ''; if (xhr.status == 0) { ls_message = 'You are offline!!\n Please Check Your Network.'; ls_logmessage = 'Disconnected' } else if (xhr.status == 404) { ls_message = 'Requested URL not found.'; ls_logmessage = 'Not Found' } else if (xhr.status == 500) { ls_message = 'Internal Server Error.'; ls_logmessage = 'Internal Server Error' } else if (thrownError == 'parsererror') { ls_message = 'Error.\nParsing JSON Request failed.' } else if (thrownError == 'timeout') { ls_message = 'Request Time out.'; ls_logmessage = 'Request Time out' } else { ls_message = 'Unknow Error.\n' + xhr.responseText; ls_logmessage = 'Unknow Error' } addLog('Response Page From [<a href="' + ls_url + '">' + ls_url + '</a>] is <b>' + nl2br(ls_logmessage) + '</b><br /><br />' + nl2br(htmlentities(xhr.responseText)), 'error'); alert(ls_message); setLoading(false); }, dataType: "html"
    });
};

// Uniform UI (Called after page loaded)
var uniform = function() {
	// Linkbutton
	$('#container .easyui-linkbutton').linkbutton({  
		plain:true  
	}); 
	/*$('#container .easyui-linkbutton').each(function(i,el){ 
		if($(el).attr('plain')=='false'){
			$(el).linkbutton();  
		} else {
			$(el).linkbutton({  
				plain:true  
			});
		}
	});*/
	
    // Generate Tooltips
    $('.tooltips').each(function(i, obj) { var ls_title = $(obj).attr('title'); if (ls_title != undefined && ls_title != null && ls_title != '') { $(obj).tipTip({ edgeOffset: 10 }); } });
    
};

var gs_popup_itteration = 0; var gs_popup_lock = false;
var openPopup	= function(ao_param1, ao_param2){
	var ls_url	= (ao_param1!=undefined && typeof(ao_param1)=='string' && trim(ao_param1)!='' ? ao_param1 : '');
	if(ao_param1==undefined){ ao_option={}; }else if(typeof(ao_param1)=='object'){ ao_option=ao_param1; }else if(typeof(ao_param2)=='object'){ ao_option=ao_param2; }else{ ao_option={}; }
	var ls_title	= (ao_option.title==undefined ? '' : ao_option.title);
	if(ao_option.url!=undefined && ao_option.url!='') ls_url = ao_option.url;
	var ln_width	= (ao_option.width==undefined ? 780 : ao_option.width);
	var ln_height	= (ao_option.height==undefined ? 450 : ao_option.height);
	var lo_position	= (ao_option.position==undefined ? null : ao_option.position);
	var lf_onOpen	= (ao_option.open==undefined || typeof(ao_option.open)!='function') ? function(){} : ao_option.open;
	var lf_onClose	= (ao_option.close==undefined || typeof(ao_option.close)!='function') ? function(){} : ao_option.close;
	
	var ls_html = '<br /> &nbsp; &nbsp; &nbsp; <img src="'+gs_path+'/content/images/spinner.gif" border="0" alt="" />  Loading..';
	var container_id	= 'popup'+gs_popup_itteration;
	var $container		= $('<div>').css('display','none').attr('id',container_id).html(ls_html).data('onClose', lf_onClose);
	$('body').append($container);
	
	var $popup = $('#popup'+gs_popup_itteration).dialog({
		title	: ls_title,
		width	: ln_width,
		height	: ln_height,
		modal	: true,
		buttons : (ao_option.buttons == undefined ? null : ao_option.buttons),
		//position: lo_position,
		onOpen: function() {
			if(ls_url!=''){
				$('#'+container_id+' .dialog-content').html('<br /> &nbsp;  &nbsp; <img src="'+gs_path+'/content/images/spinner.gif" /> Loading..').show();
				$('#'+container_id+' .dialog-button').hide();
				$.ajax({
					type: 'POST', url: ls_url, cache: false, data: { ajax: '1', popup:'1', culture: gs_localize, sessid: sessid },
					success: function(data) { addLog('Response Page From [<a href="' + ls_url + '">' + ls_url + '</a>]<br />' + nl2br(htmlentities(data)), 'success'); $('#'+container_id+' .dialog-content').html(data).show(); $('#'+container_id+' .dialog-button').show(); if (debug) { $('.debug_url').show(); } else { $('.debug_url').hide(); } uniform(); lf_onOpen.call(document.getElementById(container_id));  },
					error: function(xhr, ajaxOptions, thrownError) { var ls_message = ''; var ls_logmessage = ''; if (xhr.status == 0) { ls_message = 'You are offline!!\n Please Check Your Network.'; ls_logmessage = 'Disconnected' } else if (xhr.status == 404) { ls_message = 'Requested URL not found.'; ls_logmessage = 'Not Found' } else if (xhr.status == 500) { ls_message = 'Internal Server Error.'; ls_logmessage = 'Internal Server Error' } else if (thrownError == 'parsererror') { ls_message = 'Error.\nParsing JSON Request failed.' } else if (thrownError == 'timeout') { ls_message = 'Request Time out.'; ls_logmessage = 'Request Time out' } else { ls_message = 'Unknow Error.\n' + xhr.responseText; ls_logmessage = 'Unknow Error' } addLog('Response Page From [<a href="' + ls_url + '">' + ls_url + '</a>] is <b>' + nl2br(ls_logmessage) + '</b><br /><br />' + nl2br(htmlentities(xhr.responseText)), 'error'); $('#'+container_id).html(ls_message); }, dataType: "html"
				});	
				
			}else{ lf_onOpen.call(document.getElementById(container_id));  }
		},
		onClose: function() { closePopup(true);}
	});
	
	gs_popup_itteration++;
	
	return $popup;
};
var closePopup = function(ui){
	if(ui==undefined || !ui || ui==null){ if(gs_popup_lock) return false; gs_popup_lock = true; }
	gs_popup_itteration--;
	
	if($('#popup'+gs_popup_itteration).length > 0){
		var lf_close	= $('#popup'+gs_popup_itteration).data('onClose');
		lf_close.call(document.getElementById('popup'+gs_popup_itteration));
		
		$('#popup'+gs_popup_itteration).dialog('destroy');
		$('#popup'+gs_popup_itteration).remove();
	}
	if(gs_popup_lock){ setInterval('gs_popup_lock=false;', 1000); }
};

var padlength = function(what){ return (what.toString().length==1)? "0"+what : what; };

var D   = new Array("Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
var M   = new Array("Januari","Pebruari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember");

var updateClock = function(){
	var day =now.getDay();
	var dstr= D[now.getDay()]+", "+padlength(now.getDate())+" "+M[now.getMonth()]+" "+now.getFullYear();
	var tstr=padlength(now.getHours())+":"+padlength(now.getMinutes())+":"+padlength(now.getSeconds());
	$("#cont_clock").html(dstr+" | "+tstr);
};

$(document).ready(function() {
	//if ($.browser.msie){ block_ie(); return false; }
    containerResize(); uniform();
    $(window).resize(containerResize);

    $('#content_block').fadeOut('medium');
    $('#content_loading').fadeOut('slow', function() { $('#content_block').removeAttr('style'); });

    /*$('.fg-button').hover(
        function() { $(this).removeClass('ui-state-default').addClass('ui-state-focus'); },
        function() { $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }
    );

    // Menu
    $('#menu').button({ icons: { secondary: "ui-icon-triangle-1-s"} })
              .fgmenu(    //{ content: $('#menu').next().html(), flyOut: true }
                        {content: $('#menu').next().html(), backLink: false, flagClass: 'sys_menu' }
                    );

    $('#btn_home').button({ icons: { primary: 'ui-icon-home' }, text: false }).css('padding-right', '35px');
    $('#btn_bookmark').button({ icons: { primary: 'ui-icon-star', secondary: 'ui-icon-triangle-1-s' }, text: false }).css('padding-right', '35px');
    $('#btn_goto').button({ icons: { primary: 'ui-icon-circle-arrow-e' }, text: false }).css('padding-right', '35px');

    $('#btn_sysmessage').button({ icons: { primary: 'ui-icon-mail-closed' }, text: true });
    $('#btn_sysdebug').button({ icons: { primary: 'ui-icon-alert' }, text: false }).css('padding-right', '35px').click(function() { $('#content_debug').dialog({ title: 'Debuging Application', resizable: false, width: 500, height: 400, buttons: { "Clear Log": function() { $('#content_debug').html(''); }, "Close": function() { $(this).dialog("close"); } } }); });
    $('#btn_syshelp').button({ icons: { primary: 'ui-icon-help' }, text: false }).css('padding-right', '35px');
    $('#btn_sysconfig').button({ icons: { primary: 'ui-icon-wrench' }, text: false }).css('padding-right', '35px').click(function() { $('#content_config').dialog({ title: 'Configuration', resizable: false, width: 500, height: 400, buttons: { "Save": function() { $('#content_config').html(''); }, "Close": function() { $(this).dialog("close"); } } }); });
    $('#btn_syslogout').button({ icons: { primary: 'ui-icon-power' }, text: false }).css('padding-right', '35px').click(function() { $('#content_logout').dialog({ title: 'Logout Application ?', resizable: false, modal: true, width: 320, height: 170, buttons: { "Cancel": function() { $(this).dialog("close"); }, "Logout": function() { redirect(gs_path+'/app/logout'); } } }); });

    $('.button_set').buttonset();*/
	
	//$('#menu').fgmenu({content: $('#menu').next().html(), backLink: false, flagClass: 'sys_menu' });
	
	$('.easyui-tree').each(function(i,ul){
		$(ul).tree({ url: gs_path+'/app/submenu_data/?menu_id=' + $(ul).attr('rel'), animate:true, onClick: function(item){ if(item.attributes.url!=undefined); loadPage(item.attributes.url, { menu_id:item.attributes.menu_id }); return false; } });
	});
	
	$('#btn_sysconfig').click(function() {
		$('#content_config').dialog({	title: 'Configuration', resizable: false, modal:true, width: 500, height: 400, 
										buttons:[	{ text:'Save', iconCls:'icon-save', handler:function(){ alert('ok'); } },
													{ text:'Close', iconCls:'icon-cancel', handler:function(){ $('#content_config').dialog('close'); } }]
		}); 
	});
	
	$('#btn_sysmessage').click(function() {
		loadPage( '/it_message/index/?user='+urlencode(userid));
	});
	
	
	
	$('#btn_syslogout').click(function() { $.messager.confirm(' &nbsp; ', 'Are you sure want to logout ?', function(r){ if (r){ redirect(gs_path+'/app/logout'); } }); });

	$('#btn_sysuser').click(function() {
		var $popup = openPopup({ title: '&nbsp;',
					                width: 564,
					                height: 460,
					                url: gs_path + '/ituserid/edit/?readonly_role=true&user_id=' + urlencode(userid),
					                buttons: [{
					                    text: 'Save',
					                    iconCls: 'icon-save',
					                    handler: function() {
					                        $('#form_popup').submitForm('/ituserid/ajax_post', { onComplete: function() { closePopup(); } });
					                    }
					                }, {
					                    text: 'Close',
					                    iconCls: 'icon-cancel',
					                    handler: function() {
					                        closePopup();
					                    }
                                    }],
					                    onComplete: function() { $('#form_popup').data('mode', 'edit'); }
					            });
	});

    sessid = Base64Decode(gs_app); debug = $('#chk_debug').attr('checked') == 'checked';
    $('#chk_debug').change(function() { debug = $('#chk_debug').attr('checked') == 'checked'; });
    setInterval("now.setSeconds(now.getSeconds()+1); updateClock();", 1000);
	
	$('#container').scroll(function () { 
		//var ln_offset = parseInt(getYOffset()-16);
		var ln_offset = $(this).scrollTop() - 11;
		
		if(ln_offset<0) ln_offset = 0;
		$('.content_box .head').css('margin-top', ln_offset +'px');
		if(ln_offset>0){ 
			var ln_parentwidth = $('.content_box .head').parent().width();
			var ls_width = ln_parentwidth==undefined||ln_parentwidth==null||ln_parentwidth==0||ln_parentwidth=='' ? '100%' : ln_parentwidth+'px';
			//$('.content_box .head').css('position','absolute').css('width',ls_width); 
			$('.content_box .head').css('position','fixed').css('margin-top','-10px').css('width',ls_width); 
		}else{
			$('.content_box .head').css('position','relative'); 
		}
	});
});